//
//  MYComposeViewController.swift
//  NewMicroblog
//
//  Created by apple on 2016/11/1.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class MYComposeViewController: UIViewController {
    fileprivate lazy var titleLabel:UILabel = {
        let label = UILabel()
        label.textColor = UIColor.darkGray
        label.font = UIFont.systemFont(ofSize: 17)
        label.textAlignment = .center
        label.numberOfLines = 0
        if let name = MYUserinfoViewModel.sharedModel.userInfoModel?.screen_name{
            let title = "发微博\n" + name
            let attrbuteStr: NSMutableAttributedString = NSMutableAttributedString(string: title)
            let range = (title as NSString).range(of: name)
            attrbuteStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName:UIColor.brown], range: range)
            label.attributedText = attrbuteStr
        }else{
            label.text = "发微博"
        }
        label.sizeToFit()
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //MARK:- 搭建主界面
    private func setupUI(){
        view.backgroundColor = UIColor.white
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameChang(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        setupNav()
        navigationItem.rightBarButtonItem?.isEnabled = false
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        textView.snp_makeConstraints { (make) in
            make.top.leading.trailing.equalTo(view);
            make.bottom.equalTo(toolBar.snp_top)
        }
        toolBar.snp_makeConstraints { (make) in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(35)
        }
        pictureView.snp_makeConstraints { (make) in
            make.centerX.equalTo(textView)
            make.top.equalTo(textView).offset(100)
            make.height.equalTo(textView.snp_width).offset(-20)
            make.width.equalTo(textView).offset(-20)
        }
    }
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancleAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        navigationItem.titleView = titleLabel
    }
    fileprivate lazy var rightBtn: UIButton = {
        let rightBtn = UIButton(setImage: nil, title: "发送", tagart: self, action: #selector(sendAction))
        rightBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        rightBtn.setBackgroundImage(UIImage(named:"common_button_orange"), for: .normal)
        rightBtn.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: .disabled)
        rightBtn.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: .highlighted)
        
        rightBtn.size = CGSize(width: 50, height: 35)
        return rightBtn
    }()
    
    fileprivate lazy var emoticonKeyBoard: MYEmoticonKeyBoard = {
       let keyboard = MYEmoticonKeyBoard()
        keyboard.size = CGSize(width: self.textView.width, height: 216)
        return keyboard
    }()
    
    /// 取消操作
    func cancleAction(){
        self.view.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    
    /// 发送数据
    func sendAction(){
        let token = MYUserinfoViewModel.sharedModel.accessToken
        let status = textView.text
        SVProgressHUD.show()
        if pictureView.images.count > 0 {
            let image = pictureView.images.first!
            MYNetworkingTool.shareTool.uploadImage(token: token!, status: status!, image: image, success: { (res) in
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            }, failure: { (error) in
                print(error)
                SVProgressHUD.showError(withStatus: "发送失败")
            })
            return
        }
        MYNetworkingTool.shareTool.update(token: token!, status: status!, success: { (res) in
            SVProgressHUD.showSuccess(withStatus: "发送成功")
        }, failure: {(error) in
            print(error)
            SVProgressHUD.showError(withStatus: "发送失败")
        })
    }
    ///添加toolBar
    fileprivate lazy var toolBar:MYComposeToolBar = {
      let composeTool = MYComposeToolBar()
        composeTool.callBack = {[weak self] (type: MYComposeButtonType) in
            switch type{
            case .picture:
                print("pic")
                self?.didSelectPicture()
            case .mention:
                print("mention")
            case .trend:
                print("trend")
            case .emoticon:
                print("emoticon")
                self?.didSelectEmotion()
            case .add:
                print("dd")
            }
        }
        return composeTool
    }()
    fileprivate lazy var pictureView: MYComposeCollectionView = {
        let view = MYComposeCollectionView()
        view.backgroundColor = self.textView.backgroundColor
        view.callBack = {[weak self] in
            self?.didSelectPicture()
        }
        return view
    }()

    
    ///添加textView 输入框
    fileprivate lazy var textView: MYComposeTextView = {
       let textView = MYComposeTextView()
        textView.placeHolder = "我的老婆确实很漂亮"
        textView.font = UIFont.systemFont(ofSize: 14)
         textView.delegate = self
        ///允许textView可以滚动
        textView.alwaysBounceVertical = true
        return textView
    }()
    
    /// 监听键盘frame的变化
    @objc private func keyboardFrameChang(noti:NSNotification){
        let keyFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        toolBar.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyFrame.origin.y - SCREENHEIGHT)
        }
        UIView.animate(withDuration: duration, animations: {
            self.view.layoutIfNeeded()
        })
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }


}

// MARK: - UITextViewDelegate
extension MYComposeViewController: UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        //判断是否有内容，按钮确定可不可用
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    /// 点击图片的浏览器
    func didSelectPicture(){
        let imgPickerVc = UIImagePickerController()
        imgPickerVc.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imgPickerVc.sourceType = .camera
        }else{
            imgPickerVc.sourceType = .photoLibrary
        }
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            
        }
        if UIImagePickerController.isCameraDeviceAvailable(.rear){
            
        }
        imgPickerVc.allowsEditing = true
        self.present(imgPickerVc, animated: true, completion: nil)
    }
    
    
}

// MARK: - UIImagePickerControllerDelegate,UINavigationControllerDelegate
extension MYComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let newImage = self.scaleImage(scaleWidth: 200, image: image)
        pictureView.addImage(image:newImage)
        picker.dismiss(animated: true, completion: nil)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    ///将图片进行等比例压缩
    private func scaleImage(scaleWidth: CGFloat,image: UIImage) -> UIImage{
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
        UIGraphicsBeginImageContext(scaleSize)
        image.draw(in: CGRect(origin: CGPoint.zero, size: scaleSize))
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return currentImage!
    }
    ///点击表情处理逻辑
    func didSelectEmotion() {
        if textView.inputView == nil {
            toolBar.showIcon(isEmoticon: true)
            textView.inputView = emoticonKeyBoard
        }else{
            textView.inputView = nil
            toolBar.showIcon(isEmoticon: false)
        }
        textView.becomeFirstResponder()
        textView.reloadInputViews()
    }
    
}


